<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="theme-color" content="#0078E7"><meta name="author" content="呆航"><meta name="copyright" content="呆航"><meta name="generator" content="Hexo 5.2.0"><meta name="theme" content="hexo-theme-yun"><title>如何写一个qq机器人 | 呆航的小站</title><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@900&amp;display=swap" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/star-markdown-css@0.1.25/dist/yun/yun-markdown.min.css"><script src="//at.alicdn.com/t/font_1140697_dxory92pb0h.js" async></script><script src="https://cdn.jsdelivr.net/npm/scrollreveal/dist/scrollreveal.min.js" defer></script><script>function initScrollReveal() {
  [".post-card",".post-content img"].forEach((target)=> {
    ScrollReveal().reveal(target);
  })
}
document.addEventListener("DOMContentLoaded", initScrollReveal);
document.addEventListener("pjax:success", initScrollReveal);
</script><link id="light-prism-css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@latest/themes/prism.css" media="(prefers-color-scheme: light)"><link id="dark-prism-css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@latest/themes/prism-tomorrow.css" media="(prefers-color-scheme: dark)"><link rel="icon" type="image/svg+xml" href="/yun.svg"><link rel="mask-icon" href="/yun.svg" color="#0078E7"><link rel="preload" href="/css/hexo-theme-yun.css" as="style"><link rel="preload" href="/js/utils.js" as="script"><link rel="preload" href="/js/hexo-theme-yun.js" as="script"><link rel="prefetch" href="/js/sidebar.js" as="script"><link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin><script id="yun-config">
    const Yun = window.Yun || {};
    window.CONFIG = {"hostname":"lqh827821562.gitee.io","root":"/","title":"呆航的小站","version":"1.7.0","mode":"auto","copycode":true,"page":{"isPost":true},"i18n":{"placeholder":"搜索...","empty":"找不到您查询的内容: ${query}","hits":"找到 ${hits} 条结果","hits_time":"找到 ${hits} 条结果（用时 ${time} 毫秒）"},"anonymous_image":"https://cdn.jsdelivr.net/gh/YunYouJun/cdn/img/avatar/none.jpg","say":{"api":"https://v1.hitokoto.cn","hitokoto":true},"algolia":{"appID":"E0XRZBP9EC","apiKey":"014277189b8673da64c5c3a931019c0e","indexName":"blog","hits":{"per_page":10}},"fireworks":{"colors":["102, 167, 221","62, 131, 225","33, 78, 194"]}};
  </script><link rel="stylesheet" href="/css/hexo-theme-yun.css"><script src="/js/utils.js"></script><script src="/js/hexo-theme-yun.js"></script><link rel="alternate" href="/atom.xml" title="呆航的小站" type="application/atom+xml"><link rel="preconnect" href="https://www.google-analytics.com" crossorigin><script async src="https://www.googletagmanager.com/gtag/js?id=UA-121354150-1"></script><script>if (CONFIG.hostname === location.hostname) {
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-121354150-1');
}</script><script data-ad-client="ca-pub-2245427233262012" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(function(){
  var bp = document.createElement('script');
  var curProtocol = window.location.protocol.split(':')[0];
  if (curProtocol === 'https') {
    bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
  }
  else {
    bp.src = 'http://push.zhanzhang.baidu.com/push.js';
  }
  var s = document.getElementsByTagName("script")[0];
  s.parentNode.insertBefore(bp, s);
})();</script><!-- Google Tag Manager --><script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M9KWR9L');</script><!-- End Google Tag Manager --><meta name="description" content="众所周知，我们需要给女朋友发早安晚安，如果有一天忘了，容易把我们吓死（bushi），所以qq机器人的需求诞生了。 准备工作下载go-cqhttp安装python环境具体细节可参考网上资源 go-cqhttp使用在命令行中输入go-cqhttp（需要在解压好的目录下运行）运行好后选择HTTP通信在生成的config.yml中进行qq账号密码的相关配置配置完成后可在命令行中输入go-cqhttp进行登">
<meta property="og:type" content="article">
<meta property="og:title" content="如何写一个qq机器人">
<meta property="og:url" content="http://lqh827821562.gitee.io/%E5%A6%82%E4%BD%95%E5%86%99%E4%B8%80%E4%B8%AAqq%E6%9C%BA%E5%99%A8%E4%BA%BA/index.html">
<meta property="og:site_name" content="呆航的小站">
<meta property="og:description" content="众所周知，我们需要给女朋友发早安晚安，如果有一天忘了，容易把我们吓死（bushi），所以qq机器人的需求诞生了。 准备工作下载go-cqhttp安装python环境具体细节可参考网上资源 go-cqhttp使用在命令行中输入go-cqhttp（需要在解压好的目录下运行）运行好后选择HTTP通信在生成的config.yml中进行qq账号密码的相关配置配置完成后可在命令行中输入go-cqhttp进行登">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s1.ax1x.com/2022/06/27/jZmvuj.png">
<meta property="og:image" content="https://s1.ax1x.com/2022/06/27/jZnk2F.png">
<meta property="article:published_time" content="2022-06-27T15:12:24.000Z">
<meta property="article:modified_time" content="2022-06-27T15:43:31.846Z">
<meta property="article:author" content="呆航">
<meta property="article:tag" content="便利">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://s1.ax1x.com/2022/06/27/jZmvuj.png"><script src="/js/ui/mode.js"></script></head><body><script defer src="https://cdn.jsdelivr.net/npm/animejs@latest"></script><script defer src="/js/ui/fireworks.js"></script><canvas class="fireworks"></canvas><div class="container"><a class="sidebar-toggle hty-icon-button" id="menu-btn"><div class="hamburger hamburger--spin" type="button"><span class="hamburger-box"><span class="hamburger-inner"></span></span></div></a><div class="sidebar-toggle sidebar-overlay"></div><aside class="sidebar"><script src="/js/sidebar.js"></script><ul class="sidebar-nav"><li class="sidebar-nav-item sidebar-nav-toc hty-icon-button sidebar-nav-active" data-target="post-toc-wrap" title="文章目录"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-list-ordered"></use></svg></li><li class="sidebar-nav-item sidebar-nav-overview hty-icon-button" data-target="site-overview-wrap" title="站点概览"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-passport-line"></use></svg></li></ul><div class="sidebar-panel" id="site-overview-wrap"><div class="site-info fix-top"><a class="site-author-avatar" href="/about/" title="呆航"><img width="96" loading="lazy" src="/images/avatar.png" alt="呆航"><span class="site-author-status" title="Looking for dawn.">🌑</span></a><div class="site-author-name"><a href="/about/">呆航</a></div><span class="site-name">呆航的小站</span><sub class="site-subtitle">All at sea.</sub><div class="site-desciption">希望能成为一个有趣的人</div></div><nav class="site-state"><a class="site-state-item hty-icon-button icon-home" href="/" title="首页"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-home-4-line"></use></svg></span></a><div class="site-state-item"><a href="/archives/" title="归档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-archive-line"></use></svg></span><span class="site-state-item-count">42</span></a></div><div class="site-state-item"><a href="/categories/" title="分类"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-folder-2-line"></use></svg></span><span class="site-state-item-count">2</span></a></div><div class="site-state-item"><a href="/tags/" title="标签"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="site-state-item-count">9</span></a></div><a class="site-state-item hty-icon-button" target="_blank" rel="noopener" href="https://yun.yunyoujun.cn" title="文档"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-settings-line"></use></svg></span></a></nav><hr style="margin-bottom:0.5rem"><div class="links-of-author"><a class="links-of-author-item hty-icon-button" rel="noopener" href="tencent://message/?uin=827821562&amp;site=qq&amp;menu=yes" title="QQ" target="_blank" style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></a></div><hr style="margin:0.5rem 1rem"><div class="links"><a class="links-item hty-icon-button" href="/links/" title="我的小伙伴们" style="color:dodgerblue"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-genderless-line"></use></svg></a></div><br><a class="links-item hty-icon-button" id="toggle-mode-btn" href="javascript:;" title="Mode" style="color: #f1cb64"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-contrast-2-line"></use></svg></a></div><div class="sidebar-panel sidebar-panel-active" id="post-toc-wrap"><div class="post-toc"><div class="post-toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C"><span class="toc-number">1.</span> <span class="toc-text">准备工作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#go-cqhttp%E4%BD%BF%E7%94%A8"><span class="toc-number">2.</span> <span class="toc-text">go-cqhttp使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#python"><span class="toc-number">3.</span> <span class="toc-text">python</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B6%E4%BB%96%E5%8F%AF%E8%A1%8C%E4%BB%A3%E7%A0%81"><span class="toc-number">3.1.</span> <span class="toc-text">其他可行代码</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9C%BA%E5%99%A8%E4%BA%BA%E9%83%A8%E7%BD%B2"><span class="toc-number">4.</span> <span class="toc-text">机器人部署</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B8%A9%E9%A6%A8%E6%8F%90%E7%A4%BA"><span class="toc-number">5.</span> <span class="toc-text">温馨提示</span></a></li></ol></div></div></div></aside><main class="sidebar-translate" id="content"><div id="post"><article class="hty-card post-block" itemscope itemtype="https://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://lqh827821562.gitee.io/%E5%A6%82%E4%BD%95%E5%86%99%E4%B8%80%E4%B8%AAqq%E6%9C%BA%E5%99%A8%E4%BA%BA/"><span hidden itemprop="author" itemscope itemtype="https://schema.org/Person"><meta itemprop="name" content="呆航"><meta itemprop="description"></span><span hidden itemprop="publisher" itemscope itemtype="https://schema.org/Organization"><meta itemprop="name" content="呆航的小站"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">如何写一个qq机器人</h1><div class="post-meta"><div class="post-time" style="display:block"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-calendar-line"></use></svg></span> <time title="创建时间：2022-06-27 23:12:24" itemprop="dateCreated datePublished" datetime="2022-06-27T23:12:24+08:00">2022-06-27</time></div><span class="post-count"><span class="post-symbolcount"><span class="post-meta-item-icon" title="本文字数"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-file-word-line"></use></svg></span> <span title="本文字数">1.3k</span><span class="post-meta-divider">-</span><span class="post-meta-item-icon" title="阅读时长"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-timer-line"></use></svg></span> <span title="阅读时长">5m</span></span></span><span class="post-busuanzi"><span class="post-meta-divider">-</span><span class="post-meta-item-icon" title="阅读次数"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-eye-line"></use></svg> <span id="busuanzi_value_page_pv"></span></span></span><div class="post-classify"><span class="post-tag"><a class="tag-item" href="/tags/%E4%BE%BF%E5%88%A9/" style="--text-color:dimgray"><span class="post-meta-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-price-tag-3-line"></use></svg></span><span class="tag-name">便利</span></a></span></div></div></header><section class="post-body" itemprop="articleBody"><div class="post-content markdown-body" style="--smc-primary:#0078E7;"><p>众所周知，我们需要给女朋友发早安晚安，如果有一天忘了，容易把我们吓死（bushi），所以qq机器人的需求诞生了。</p>
<h2 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h2><p>下载<a target="_blank" rel="noopener" href="https://github.com/Mrs4s/go-cqhttp/releases">go-cqhttp</a><br>安装python环境<br>具体细节可参考网上资源</p>
<h2 id="go-cqhttp使用"><a href="#go-cqhttp使用" class="headerlink" title="go-cqhttp使用"></a>go-cqhttp使用</h2><p><a target="_blank" rel="noopener" href="https://imgtu.com/i/jZmvuj"><img src="https://s1.ax1x.com/2022/06/27/jZmvuj.png" alt="jZmvuj.png" loading="lazy"></a><br>在命令行中输入go-cqhttp（需要在解压好的目录下运行）运行好后选择HTTP通信<br>在生成的config.yml中进行qq账号密码的相关配置<br><a target="_blank" rel="noopener" href="https://imgtu.com/i/jZnk2F"><img src="https://s1.ax1x.com/2022/06/27/jZnk2F.png" alt="jZnk2F.png" loading="lazy"></a><br>配置完成后可在命令行中输入go-cqhttp进行登录，注意这里有一个细节，如果登录过程需要手机扫码登录，且手机显示页面为不安全须在同一个wlan下进行登录的话（此处主要应用于将本机器人挂在云服务器上），可以先在本地完成一次以上步骤，然后将生成的device.json 与 session.token复制到云服务器上<br>登录后可使用<code>http://127.0.0.1:5700/send_private_msg?user_id=发送目标的qq号&amp;message=要发送的信息</code>进行验证，如果成功发送出去，则配置正确。<br>运行过程中包含warning上报失败属于正常现象无需理会  </p>
<h2 id="python"><a href="#python" class="headerlink" title="python"></a>python</h2><p>首先，我们将几个常用的代码封装成函数,前者是发送消息所使用的函数，后者是接收各类事件所用函数</p>
<pre class="language-python" data-language="python"><code class="language-python"><span class="token keyword">import</span> socket
<span class="token keyword">import</span> json
ListenSocket <span class="token operator">=</span> socket<span class="token punctuation">.</span>socket<span class="token punctuation">(</span>socket<span class="token punctuation">.</span>AF_INET<span class="token punctuation">,</span> socket<span class="token punctuation">.</span>SOCK_STREAM<span class="token punctuation">)</span>
ListenSocket<span class="token punctuation">.</span>bind<span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token string">'127.0.0.1'</span><span class="token punctuation">,</span> <span class="token number">5701</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
ListenSocket<span class="token punctuation">.</span>listen<span class="token punctuation">(</span><span class="token number">100</span><span class="token punctuation">)</span>
HttpResponseHeader <span class="token operator">=</span> <span class="token triple-quoted-string string">'''HTTP/1.1 200 OK
Content-Type: text/html
'''</span>
<span class="token keyword">def</span> <span class="token function">request_to_json</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token builtin">len</span><span class="token punctuation">(</span>msg<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> msg<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token operator">==</span><span class="token string">"&#123;"</span> <span class="token keyword">and</span> msg<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token operator">==</span><span class="token string">"\n"</span><span class="token punctuation">:</span>
            <span class="token keyword">return</span> json<span class="token punctuation">.</span>loads<span class="token punctuation">(</span>msg<span class="token punctuation">[</span>i<span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token boolean">None</span>
<span class="token comment">#需要循环执行，返回值为json格式</span>
<span class="token keyword">def</span> <span class="token function">rev_msg</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token comment"># json or None</span>
    Client<span class="token punctuation">,</span> Address <span class="token operator">=</span> ListenSocket<span class="token punctuation">.</span>accept<span class="token punctuation">(</span><span class="token punctuation">)</span>
    Request <span class="token operator">=</span> Client<span class="token punctuation">.</span>recv<span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">)</span><span class="token punctuation">.</span>decode<span class="token punctuation">(</span>encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span>
    rev_json<span class="token operator">=</span>request_to_json<span class="token punctuation">(</span>Request<span class="token punctuation">)</span>
    Client<span class="token punctuation">.</span>sendall<span class="token punctuation">(</span><span class="token punctuation">(</span>HttpResponseHeader<span class="token punctuation">)</span><span class="token punctuation">.</span>encode<span class="token punctuation">(</span>encoding<span class="token operator">=</span><span class="token string">'utf-8'</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    Client<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> rev_json

<span class="token keyword">def</span> <span class="token function">send_msg</span><span class="token punctuation">(</span>resp_dict<span class="token punctuation">)</span><span class="token punctuation">:</span>
    client <span class="token operator">=</span> socket<span class="token punctuation">.</span>socket<span class="token punctuation">(</span>socket<span class="token punctuation">.</span>AF_INET<span class="token punctuation">,</span> socket<span class="token punctuation">.</span>SOCK_STREAM<span class="token punctuation">)</span>
    ip <span class="token operator">=</span> <span class="token string">'127.0.0.1'</span>
    client<span class="token punctuation">.</span>connect<span class="token punctuation">(</span><span class="token punctuation">(</span>ip<span class="token punctuation">,</span> <span class="token number">5700</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    msg_type <span class="token operator">=</span> resp_dict<span class="token punctuation">[</span><span class="token string">'msg_type'</span><span class="token punctuation">]</span>  <span class="token comment"># 回复类型（群聊/私聊）</span>
    number <span class="token operator">=</span> resp_dict<span class="token punctuation">[</span><span class="token string">'number'</span><span class="token punctuation">]</span>  <span class="token comment"># 回复账号（群号/好友号）</span>
    msg <span class="token operator">=</span> resp_dict<span class="token punctuation">[</span><span class="token string">'msg'</span><span class="token punctuation">]</span>  <span class="token comment"># 要回复的消息</span>
    <span class="token comment"># 将字符中的特殊字符进行url编码</span>
    msg <span class="token operator">=</span> msg<span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">" "</span><span class="token punctuation">,</span> <span class="token string">"%20"</span><span class="token punctuation">)</span>
    msg <span class="token operator">=</span> msg<span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">"\n"</span><span class="token punctuation">,</span> <span class="token string">"%0a"</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> msg_type <span class="token operator">==</span> <span class="token string">'group'</span><span class="token punctuation">:</span>
        payload <span class="token operator">=</span> <span class="token string">"GET /send_group_msg?group_id="</span> <span class="token operator">+</span> <span class="token builtin">str</span><span class="token punctuation">(</span>
            number<span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">"&amp;message="</span> <span class="token operator">+</span> msg <span class="token operator">+</span> <span class="token string">" HTTP/1.1\r\nHost:"</span> <span class="token operator">+</span> ip <span class="token operator">+</span> <span class="token string">":5700\r\nConnection: close\r\n\r\n"</span>
    <span class="token keyword">elif</span> msg_type <span class="token operator">==</span> <span class="token string">'private'</span><span class="token punctuation">:</span>
        payload <span class="token operator">=</span> <span class="token string">"GET /send_private_msg?user_id="</span> <span class="token operator">+</span> <span class="token builtin">str</span><span class="token punctuation">(</span>
            number<span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">"&amp;message="</span> <span class="token operator">+</span> msg <span class="token operator">+</span> <span class="token string">" HTTP/1.1\r\nHost:"</span> <span class="token operator">+</span> ip <span class="token operator">+</span> <span class="token string">":5700\r\nConnection: close\r\n\r\n"</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"发送"</span> <span class="token operator">+</span> payload<span class="token punctuation">)</span>
    client<span class="token punctuation">.</span>send<span class="token punctuation">(</span>payload<span class="token punctuation">.</span>encode<span class="token punctuation">(</span><span class="token string">"utf-8"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    client<span class="token punctuation">.</span>close<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">return</span> <span class="token number">0</span></code></pre>
<p>每日定时发送早安晚安</p>
<pre class="language-python" data-language="python"><code class="language-python"><span class="token keyword">from</span> receive <span class="token keyword">import</span> send_msg
<span class="token keyword">import</span> datetime
flag<span class="token operator">=</span><span class="token number">0</span>
<span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    qq<span class="token operator">=</span><span class="token number">2755347228</span>
    now <span class="token operator">=</span>datetime<span class="token punctuation">.</span>datetime<span class="token punctuation">.</span>now<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>now<span class="token punctuation">.</span>hour<span class="token operator">==</span><span class="token number">0</span> <span class="token keyword">and</span> now<span class="token punctuation">.</span>minute<span class="token operator">==</span><span class="token number">0</span> <span class="token keyword">and</span> flag<span class="token operator">==</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'晚安'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
        flag<span class="token operator">=</span><span class="token number">1</span>
    <span class="token keyword">elif</span> <span class="token punctuation">(</span>now<span class="token punctuation">.</span>hour<span class="token operator">==</span><span class="token number">7</span> <span class="token keyword">and</span> now<span class="token punctuation">.</span>minute<span class="token operator">==</span><span class="token number">0</span> <span class="token keyword">and</span> flag<span class="token operator">==</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'早'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
        flag<span class="token operator">=</span><span class="token number">0</span>

<span class="token comment">#因为判断的是小时和分钟，如果不设置flag，一分钟循环多少次就会发送多少次，所以使用flag来限制仅第一次运行发送</span></code></pre>
<p>请注意，此处代码非完整代码，如果报错缺少某模块，自行引入即可。</p>
<h3 id="其他可行代码"><a href="#其他可行代码" class="headerlink" title="其他可行代码"></a>其他可行代码</h3><p>可以根据收到信息的不同，回复信息（调用免费聊天机器人的相关接口）,具体格式如下  </p>
<pre class="language-python" data-language="python"><code class="language-python"><span class="token keyword">from</span> receive <span class="token keyword">import</span> rev_msg
<span class="token keyword">import</span> urllib<span class="token punctuation">.</span>request
<span class="token keyword">from</span> urllib<span class="token punctuation">.</span>parse <span class="token keyword">import</span> quote
<span class="token keyword">import</span> string
<span class="token keyword">import</span> socket
AIflag<span class="token operator">=</span><span class="token number">0</span>
<span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    rev <span class="token operator">=</span> rev_msg<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> rev <span class="token operator">==</span> <span class="token boolean">None</span><span class="token punctuation">:</span>
        <span class="token keyword">continue</span>
    <span class="token keyword">if</span> rev<span class="token punctuation">[</span><span class="token string">"post_type"</span><span class="token punctuation">]</span> <span class="token operator">==</span> <span class="token string">"message"</span><span class="token punctuation">:</span>
        <span class="token keyword">if</span> rev<span class="token punctuation">[</span><span class="token string">"message_type"</span><span class="token punctuation">]</span> <span class="token operator">==</span> <span class="token string">"private"</span><span class="token punctuation">:</span> <span class="token comment">#私聊</span>
            message<span class="token operator">=</span>rev<span class="token punctuation">[</span><span class="token string">'raw_message'</span><span class="token punctuation">]</span>
            qq <span class="token operator">=</span> rev<span class="token punctuation">[</span><span class="token string">'sender'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'user_id'</span><span class="token punctuation">]</span>
            <span class="token keyword">if</span> message<span class="token operator">==</span><span class="token string">'开启AI聊天'</span><span class="token punctuation">:</span>
                AIflag<span class="token operator">=</span><span class="token number">1</span>
                send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'已开启AI聊天,您可以对我说“菜单”获取AI功能'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
            <span class="token keyword">elif</span> message<span class="token operator">==</span><span class="token string">'关闭AI聊天'</span><span class="token punctuation">:</span>
                AIflag<span class="token operator">=</span><span class="token number">0</span>
                send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'已关闭AI聊天'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
            <span class="token keyword">elif</span> message<span class="token operator">==</span><span class="token string">'菜单'</span><span class="token punctuation">:</span>
                send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'获取天气，使用“天气日照”格式\n翻译，使用“翻译i love you”格式\n讲笑话，回复“笑话”\n歌词，使用“歌词后来”格式\n计算，使用“计算1+2”格式\n成语查询，使用“成语一生一世”格式'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
            <span class="token keyword">elif</span> <span class="token string">'自动回复'</span> <span class="token keyword">in</span> message<span class="token punctuation">:</span>
                <span class="token keyword">continue</span>
            <span class="token keyword">elif</span> <span class="token string">'face'</span> <span class="token keyword">in</span> message<span class="token punctuation">:</span>
                qq <span class="token operator">=</span> rev<span class="token punctuation">[</span><span class="token string">'sender'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'user_id'</span><span class="token punctuation">]</span>
                img <span class="token operator">=</span> rev<span class="token punctuation">[</span><span class="token string">'raw_message'</span><span class="token punctuation">]</span>
                send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> img<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
            <span class="token keyword">elif</span> <span class="token string">'image'</span> <span class="token keyword">in</span> message<span class="token punctuation">:</span>
                qq <span class="token operator">=</span> rev<span class="token punctuation">[</span><span class="token string">'sender'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'user_id'</span><span class="token punctuation">]</span>
                img<span class="token operator">=</span>rev<span class="token punctuation">[</span><span class="token string">'raw_message'</span><span class="token punctuation">]</span>
                send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> img<span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
            <span class="token keyword">elif</span> <span class="token string">'戳一戳'</span> <span class="token keyword">in</span> message<span class="token punctuation">:</span>
                qq <span class="token operator">=</span> rev<span class="token punctuation">[</span><span class="token string">'sender'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'user_id'</span><span class="token punctuation">]</span>
                send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'别戳了'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
            <span class="token keyword">else</span><span class="token punctuation">:</span>
                <span class="token keyword">if</span> AIflag<span class="token operator">==</span><span class="token number">1</span><span class="token punctuation">:</span>
                    url <span class="token operator">=</span> <span class="token string">'http://api.qingyunke.com/api.php?key=free&amp;appid=0&amp;msg='</span> <span class="token operator">+</span> message
                    s <span class="token operator">=</span> quote<span class="token punctuation">(</span>url<span class="token punctuation">,</span> safe<span class="token operator">=</span>string<span class="token punctuation">.</span>printable<span class="token punctuation">)</span>

                    <span class="token keyword">try</span><span class="token punctuation">:</span>
                        <span class="token keyword">with</span> urllib<span class="token punctuation">.</span>request<span class="token punctuation">.</span>urlopen<span class="token punctuation">(</span>s<span class="token punctuation">)</span> <span class="token keyword">as</span> response<span class="token punctuation">:</span>
                            html <span class="token operator">=</span> response<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
                            <span class="token comment"># 将获取到的响应内容进行解码，并将json字符串内容转换为python字典格式</span>
                            <span class="token comment"># 通过下标取到机器人回复的内容</span>
                            qq <span class="token operator">=</span> rev<span class="token punctuation">[</span><span class="token string">'sender'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'user_id'</span><span class="token punctuation">]</span>
                            <span class="token comment"># print(eval(html.decode("utf-8"))["content"])</span>
                            send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span>
                                    <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token builtin">eval</span><span class="token punctuation">(</span>html<span class="token punctuation">.</span>decode<span class="token punctuation">(</span><span class="token string">"utf-8"</span><span class="token punctuation">)</span><span class="token punctuation">.</span>replace<span class="token punctuation">(</span><span class="token string">'null'</span><span class="token punctuation">,</span><span class="token string">'None'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">[</span><span class="token string">'result'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'intents'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'result'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'text'</span><span class="token punctuation">]</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
                            <span class="token comment"># print(eval(html.decode("utf-8"))["content"])</span>
                    <span class="token keyword">except</span><span class="token punctuation">:</span>
                        qq <span class="token operator">=</span> rev<span class="token punctuation">[</span><span class="token string">'sender'</span><span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token string">'user_id'</span><span class="token punctuation">]</span>
                        send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'重新连接中。。。'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
                <span class="token keyword">else</span><span class="token punctuation">:</span>
                    send_msg<span class="token punctuation">(</span><span class="token punctuation">&#123;</span><span class="token string">'msg_type'</span><span class="token punctuation">:</span> <span class="token string">'private'</span><span class="token punctuation">,</span> <span class="token string">'number'</span><span class="token punctuation">:</span> qq<span class="token punctuation">,</span> <span class="token string">'msg'</span><span class="token punctuation">:</span> <span class="token string">'您的问题在本机器人中无预设回答，如果需要AI，可以对我说“开启AI聊天”，当您不需要AI时可以对我说“关闭AI聊天”'</span><span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token keyword">else</span><span class="token punctuation">:</span>  <span class="token comment"># rev["post_type"]=="meta_event":</span>
        <span class="token keyword">continue</span>
                              </code></pre>
<h2 id="机器人部署"><a href="#机器人部署" class="headerlink" title="机器人部署"></a>机器人部署</h2><p>将以上所有操作部署到云服务器中后，发现一个问题，如果将终端关闭，该机器人会自行停止，为解决此问题可以使用<code>nohup 命令 &amp;</code>来保证关闭ssh连接后代码依旧运行。</p>
<h2 id="温馨提示"><a href="#温馨提示" class="headerlink" title="温馨提示"></a>温馨提示</h2><p>聊天机器人很死板，一眼能看出来是机器人，有女朋友不易，且行且珍惜。</p>
</div><div id="reward-container"><span class="hty-icon-button button-glow" id="reward-button" title="打赏" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === &quot;none&quot;) ? &quot;block&quot; : &quot;none&quot;;"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-hand-coin-line"></use></svg></span><div id="reward-comment">如果你认为本篇博客帮助到了你，你可以请我喝个可乐</div><div id="qr" style="display:none;"><div style="display:inline-block"><a href="/images/zhifubao.png"><img loading="lazy" src="/images/zhifubao.png" alt="支付宝" title="支付宝"></a><div><span style="color:#00A3EE"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-alipay-line"></use></svg></span></div></div><div style="display:inline-block"><a href="/images/qq.png"><img loading="lazy" src="/images/qq.png" alt="QQ 支付" title="QQ 支付"></a><div><span style="color:#12B7F5"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-qq-line"></use></svg></span></div></div><div style="display:inline-block"><a href="/images/wechat.png"><img loading="lazy" src="/images/wechat.png" alt="微信支付" title="微信支付"></a><div><span style="color:#2DC100"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-wechat-pay-line"></use></svg></span></div></div></div></div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong>呆航</li><li class="post-copyright-link"><strong>本文链接：</strong><a href="http://lqh827821562.gitee.io/%E5%A6%82%E4%BD%95%E5%86%99%E4%B8%80%E4%B8%AAqq%E6%9C%BA%E5%99%A8%E4%BA%BA/" title="如何写一个qq机器人">http://lqh827821562.gitee.io/%E5%A6%82%E4%BD%95%E5%86%99%E4%B8%80%E4%B8%AAqq%E6%9C%BA%E5%99%A8%E4%BA%BA/</a></li><li class="post-copyright-license"><strong>版权声明：</strong>本博客所有文章除特别声明外，均默认采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="noopener" title="CC BY-NC-SA 4.0 "><svg class="icon"><use xlink:href="#icon-creative-commons-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-by-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-nc-line"></use></svg><svg class="icon"><use xlink:href="#icon-creative-commons-sa-line"></use></svg></a> 许可协议。</li></ul></section></article><div class="post-nav"><div class="post-nav-item"><a class="post-nav-prev" href="/kali-emergency-mode%E7%B4%A7%E6%80%A5%E6%A8%A1%E5%BC%8F%E5%A4%84%E7%90%86%E6%96%B9%E6%B3%95/" rel="prev" title="kali emergency mode紧急模式处理方法"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-left-s-line"></use></svg><span class="post-nav-text">kali emergency mode紧急模式处理方法</span></a></div><div class="post-nav-item"><a class="post-nav-next" href="/git-%E4%BD%BF%E7%94%A8/" rel="next" title="git 使用"><span class="post-nav-text">git 使用</span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-right-s-line"></use></svg></a></div></div></div><div class="hty-card" id="comment"><div id="valine-container"></div><script>Yun.utils.getScript("https://cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js", () => {
  const valineConfig = {"enable":true,"appId":"k8weiJIG9u6tXEjf9jL8pvQN-MdYXbMMI","appKey":"JtLQP97hURfluJNL00DMe8gl","placeholder":"Just go go","avatar":null,"pageSize":10,"visitor":false,"highlight":true,"recordIP":false,"enableQQ":true,"meta":["nick","mail","link"],"el":"#valine-container","lang":"zh-cn"}
  valineConfig.path = "/%E5%A6%82%E4%BD%95%E5%86%99%E4%B8%80%E4%B8%AAqq%E6%9C%BA%E5%99%A8%E4%BA%BA/"
  new Valine(valineConfig)
}, window.Valine);</script></div></main><footer class="sidebar-translate" id="footer"><div class="copyright"><span>&copy; 2019 – 2022 </span><span class="with-love" id="animate"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-cloud-line"></use></svg></span><span class="author"> 呆航</span></div><div class="powered"><span>由 <a href="https://hexo.io" target="_blank" rel="noopener">Hexo</a> 驱动 v5.2.0</span><span class="footer-separator">|</span><span>主题 - <a rel="noopener" href="https://github.com/YunYouJun/hexo-theme-yun" target="_blank"><span>Yun</span></a> v1.7.0</span></div><div class="live_time"><span>本博客已萌萌哒地运行</span><span id="display_live_time"></span><span class="moe-text">(●'◡'●)</span><script>function blog_live_time() {
  setTimeout(blog_live_time, 1000);
  const start = new Date('2021-05-17T00:00:00');
  const now = new Date();
  const timeDiff = (now.getTime() - start.getTime());
  const msPerMinute = 60 * 1000;
  const msPerHour = 60 * msPerMinute;
  const msPerDay = 24 * msPerHour;
  const passDay = Math.floor(timeDiff / msPerDay);
  const passHour = Math.floor((timeDiff % msPerDay) / 60 / 60 / 1000);
  const passMinute = Math.floor((timeDiff % msPerHour) / 60 / 1000);
  const passSecond = Math.floor((timeDiff % msPerMinute) / 1000);
  display_live_time.innerHTML = " " + passDay + " 天 " + passHour + " 小时 " + passMinute + " 分 " + passSecond + " 秒";
}
blog_live_time();
</script></div><div id="busuanzi"><span id="busuanzi_container_site_uv" title="总访客量"><span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-user-line"></use></svg></span><span id="busuanzi_value_site_uv"></span></span><span class="footer-separator">|</span><span id="busuanzi_container_site_pv" title="总访问量"><span><svg class="icon" aria-hidden="true"><use xlink:href="#icon-eye-line"></use></svg></span><span id="busuanzi_value_site_pv"></span></span><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></footer><a class="hty-icon-button" id="back-to-top" aria-label="back-to-top" href="#"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-arrow-up-s-line"></use></svg><svg class="progress-circle-container" viewBox="0 0 100 100"><circle class="progress-circle" id="progressCircle" cx="50" cy="50" r="48" fill="none" stroke="#0078E7" stroke-width="2" stroke-linecap="round"></circle></svg></a><a class="popup-trigger hty-icon-button icon-search" id="search" href="javascript:;" title="搜索"><span class="site-state-item-icon"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-search-line"></use></svg></span></a><script>window.addEventListener("DOMContentLoaded", () => {
  // Handle and trigger popup window
  document.querySelector(".popup-trigger").addEventListener("click", () => {
    document.querySelector(".popup").classList.add("show");
    setTimeout(() => {
      document.querySelector(".search-input").focus();
    }, 100);
  });

  // Monitor main search box
  const onPopupClose = () => {
    document.querySelector(".popup").classList.remove("show");
  };

  document.querySelector(".popup-btn-close").addEventListener("click", () => {
    onPopupClose();
  });

  window.addEventListener("keyup", event => {
    if (event.key === "Escape") {
      onPopupClose();
    }
  });
});
</script><script defer src="https://cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script><script defer src="https://cdn.jsdelivr.net/npm/instantsearch.js@4/dist/instantsearch.production.min.js"></script><script defer src="/js/search/algolia-search.js"></script><div class="popup search-popup"><div class="search-header"><span class="popup-btn-close close-icon hty-icon-button"><svg class="icon" aria-hidden="true"><use xlink:href="#icon-close-line"></use></svg></span></div><div class="search-input-container"></div><div class="algolia-results"><div id="algolia-stats"></div><div id="algolia-hits"></div><div class="algolia-pagination" id="algolia-pagination"></div></div></div></div></body></html>